package com.wym.charging.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wym.charging.config.SchedulingConfig;
import com.wym.charging.dao.ChargingRecordDao;
import com.wym.charging.dto.ChargeDto;
import com.wym.charging.entity.ChargingOptions;
import com.wym.charging.entity.ChargingRecord;
import com.wym.charging.entity.PowerStrip;
import com.wym.charging.entity.User;
import com.wym.charging.service.ChargingOptionsService;
import com.wym.charging.service.ChargingRecordService;
import com.wym.charging.service.PowerStripService;
import com.wym.charging.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 充电记录(ChargingRecord)表服务实现类
 *
 * @author WangYimin
 * @since 2024-12-08 22:40:50
 */
@Service("chargingRecordService")
public class ChargingRecordServiceImpl extends ServiceImpl<ChargingRecordDao, ChargingRecord> implements ChargingRecordService {
    @Autowired
    private UserService userService;
    
    @Autowired
    private ChargingOptionsService chargingOptionsService;

    @Autowired
    private PowerStripService powerStripService;

    @Autowired
    private SchedulingConfig schedulingConfig;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void charge(ChargeDto chargeDto) throws Exception {
        User user = userService.getById(chargeDto.getUserId());
        if (user == null) {
            throw new Exception("用户不存在");
        }
        PowerStrip powerStrip = powerStripService.getOne(new LambdaQueryWrapper<PowerStrip>().eq(PowerStrip::getPowerStripNumber, chargeDto.getPowerStripNumber()));
        if (powerStrip == null) {
            throw new Exception("排插不存在");
        }
        ChargingOptions chargingOptions = chargingOptionsService.getById(chargeDto.getChargingOptionsId());
        if (chargingOptions == null) {
            throw new Exception("充电选项不存在");
        }

        if (chargingOptions.getChargingDuration() > 0) {
            if (user.getMonthlySubscription()) {
                if (chargingOptions.getChargingDuration() * 60 > user.getRemainingTime()) {
                    throw new Exception("剩余时长不足");
                }
            }else {
                BigDecimal price = BigDecimal.ONE.multiply(BigDecimal.valueOf(chargingOptions.getChargingDuration()));
                if (user.getAccountBalance().add(user.getGiftBalance()).compareTo(price) < 0) {
                    throw new Exception("余额不足");
                }
            }
        }
        LocalDateTime now = LocalDateTime.now();
        ChargingRecord chargingRecord = new ChargingRecord();
        if (chargingOptions.getChargingDuration() > 0) {
            LocalDateTime chargingEndTime = now.plusSeconds(chargingOptions.getChargingDuration());
            chargingRecord.setChargingEndTime(chargingEndTime);
            chargingRecord.setTotalChargingTime(chargingOptions.getChargingDuration());
        }

        chargingRecord.setUserId(user.getId());
        chargingRecord.setChargingLocation(powerStrip.getPowerStripLocation());
        chargingRecord.setPowerStripNumber(powerStrip.getPowerStripNumber());
        chargingRecord.setChargingStatus(10);
        chargingRecord.setChargingMethod("扫码");
        chargingRecord.setChargingStartTime(now);

        //是包月
        if (user.getMonthlySubscription()) {
            chargingRecord.setPaymentMethod(20);
            chargingRecord.setRemainingBalance(BigDecimal.ZERO);
            chargingRecord.setConsumeGiftedAmount(BigDecimal.ZERO);
            chargingRecord.setMonthlyUsageDuration(chargingOptions.getChargingDuration());
        }else { //不是包月
            chargingRecord.setPaymentMethod(10);
            chargingRecord.setRemainingBalance(BigDecimal.ONE.multiply(BigDecimal.valueOf(chargingOptions.getChargingDuration())));
            chargingRecord.setConsumeGiftedAmount(BigDecimal.ZERO);
        }
        save(chargingRecord);
        if (chargingRecord.getChargingEndTime() != null) {
            Instant instant = chargingRecord.getChargingEndTime().atZone(ZoneId.systemDefault()).toInstant();
            schedulingConfig.addTriggerTask(String.valueOf(chargingRecord.getId()), () -> {
                chargingRecord.setChargingStatus(20);
                chargingRecord.setReasonForStopping("充电结束");
                if (chargingRecord.getPaymentMethod() == 10) {
                    user.setAccountBalance(user.getAccountBalance().subtract(chargingRecord.getRemainingBalance()));
                }else {
                    user.setRemainingTime(user.getRemainingTime() - chargingRecord.getMonthlyUsageDuration() * 60);
                }
                userService.updateById(user);
                updateById(chargingRecord);
                schedulingConfig.cancelTriggerTask(String.valueOf(chargingRecord.getId()));
            }, instant);
        }



    }
}

